package cn.dyp.com.logprint.ui;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

import cn.dyp.com.logprint.AppConfig;
import cn.dyp.com.logprint.R;
import cn.dyp.com.logprint.bean.LogBean;


/**
 * 日志显示Activity
 * 
 * @author asus
 *
 */
public class LogListActivity extends AppBaseActivity {
	// 标题控件
	private TextView mTitleTV;
	// 日志列表控件
	private ListView mListView;
	// 日志列表适配器
	private LogListAdapter mDataAdapter;
	// 日志数据列表
	private ArrayList<LogBean> mDataLists;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log_list);
		mTitleTV = (TextView) findViewById(R.id.title_text_view);
		mTitleTV.setText(R.string.log);

		mDataLists = new ArrayList<LogBean>();
		mListView = (ListView) findViewById(R.id.list);
		// 创建日志列表适配器
		mDataAdapter = new LogListAdapter(this, mDataLists);
		mListView.setAdapter(mDataAdapter);
		// 从文本文件中读取日志内容
		loadLogDataFromFile();
	}

	/**
	 * 另开线程从文本文件中读取日志内容
	 */
	private void loadLogDataFromFile() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				FileInputStream fileIs = null;
				ArrayList<LogBean> dataLists = new ArrayList<LogBean>();
				try {
					// 创建文件输入流
					fileIs = new FileInputStream(AppConfig.LOG_FILE_PATH);
					// 创建reader buffer
					BufferedReader buf = new BufferedReader(
							new InputStreamReader(fileIs));
					String readString = "";
					// 一行一行的读取日志文本
					while ((readString = buf.readLine()) != null) {
						// 以“][”为分隔符，取出日志各字段内容
						String logInfos[] = readString.split("\\]\\[");
						LogBean logBean = new LogBean();
						logBean.setDate(logInfos[0].replace("[", ""));// 日志日期时间
						logBean.setClientIP(logInfos[1]);// 客户端IP地址
						logBean.setUsername(logInfos[2]);// 用户名
						logBean.setOperationType(logInfos[3]);// 操作类型
						logBean.setOperationObj(logInfos[4]);// 操作对象
						logBean.setLogMsg(logInfos[5].replace("]", ""));// 日志内容
						dataLists.add(logBean);
					}
					buf.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (PatternSyntaxException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (fileIs != null) {
							// 关闭文件输入流
							fileIs.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				final ArrayList<LogBean> lists = dataLists;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDataLists.clear();
						mDataLists.addAll(lists);
						// 刷新列表
						mDataAdapter.notifyDataSetChanged();
						// 关闭等待框
						dismissLoadDialog();
					}
				});
			}
		}.start();
	}
}
